<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use Captcha;
use Illuminate\Support\Facades\Hash;
use Config;
use App\Helps\Functions;
use Illuminate\Support\Facades\Log;
use Ixudra\Curl\Facades\Curl;
use Illuminate\Support\Facades\Cache;
//use Intervention\Image\Image;
use Intervention\Image\ImageManagerStatic as Image;


class TestController extends Controller
{

	private $secret;
	private $appId;
	
	function __construct() {
       $this->appId = 'wx8ab9feb80f4bc7e4';
       $this->secret = '488dd10ac2ba499ba30559b8b16c4f5d';
   }

	public function test(){
//	   print_r(json_encode(session('user')));
		//echo Hash::make('666666');
//		echo session('uri');exit;
//		return view('home');
//		exec("mkdir E:\\test", $out);
//		print_r($out);

//		$Functions = new Functions();
//		$data['ddd'] = 'aaa';
//		$customReturn = $Functions->Post('https://xyt.sbedian.com/api/payCallback', $data);
//		print_r($customReturn);

//		Log::info('Showing user profile for user: 1');
		echo 'OK';
	}
	
	public function index(Request $request)
    {
//  	print_r(666);exit;
    	$file_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFm8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2IzV0RlWGZsU1hZdzlPNXVrVm1EAAIEqSgiVgMEAAAAAA==';
    	$save_to = './qrcode/temp.jpg';
    	$this->dlfile($file_url, $save_to);

    	// 修改指定图片的大小
		$img = Image::make('./img/timg.jpg');
		
		$imgQr = Image::make('./qrcode/temp.jpg')->resize(230, 230);

		// 插入水印, 水印位置在原图片的右下角, 距离下边距 10 像素, 距离右边距 15 像素
		//$img->insert('./qrcode/temp.jpg', 'bottom-right', 30, 20);
		$img->insert($imgQr, 'bottom-right', 225, 80);
		 
		// 将处理后的图片重新保存到其他路径
		$img->save('./img/new_avatar.jpg');
		
		echo 'ok';
    }
    
    // 下载文件
    private function dlfile($file_url, $save_to)
	{
		$content = file_get_contents($file_url);
		file_put_contents($save_to, $content);
	}
	
	public function index2(Request $request)
    {
        $code = $request->code;
		
		if (Cache::has($code)){
			$info = Cache::get($code);

			$openId = $info['openid'];

			$authHost = config('services.extend.authHost');
			$getUrl = $authHost.'/auth/getUserQrCode/' . $openId;
			$qrInfo = Curl::to($getUrl)->get();
			$qrInfo = json_decode($qrInfo, true);
			return redirect('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$qrInfo['data']['wpuQRTicket']);
		}
		
        if ($code) {

			//获取用户信息
			$info = $this->getInfo($code);
			if (!isset($info['openid'])){
				print_r($info);exit;
			}
			
			Cache::put($code, $info, 1);
            //更新获取的最新信息到用户表
//			exit;
//			foreach($info as $k=>$v){ 
//				echo $k."=>".$v."<br />"; 
//			}
//			exit;

			$openId = $info['openid'];

			$authHost = config('services.extend.authHost');
			$getUrl = $authHost.'/auth/getUserQrCode/'.$openId;
			$qrInfo = Curl::to($getUrl)->get();
//			print_r($qrInfo);exit;
			$qrInfo = json_decode($qrInfo, true);
			if ($qrInfo['code'] == 1){
				return redirect('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$qrInfo['data']['wpuQRTicket']);
			}else{
				return $qrInfo['msg'];
			}
			
       }
    }

    /**
     * 通过code换取网页授权access_token
     *
     * @return mixed
     */
    private function getInfo($code)
    {
        //从redis中获取有效的access_token
//      $access_token = Cache::get('access_token');
//
//      if ($access_token) return $access_token;

//      $curl = Curl::to('https://qyapi.weixin.qq.com/cgi-bin/gettoken')
//          ->withData(['corpId' => $this->corpId, 'corpsecret'=> $this->secret])
//          ->get();
        $data = Curl::to('https://api.weixin.qq.com/sns/oauth2/access_token')
            ->withData(['appid' => $this->appId, 'secret'=> $this->secret, 'code' => $code, 'grant_type' => 'authorization_code'])
            ->get();

//		{ "access_token":"ACCESS_TOKEN",
//		"expires_in":7200,
//		"refresh_token":"REFRESH_TOKEN",
//		"openid":"OPENID",
//		"scope":"SCOPE" }
//		print_r($data);exit;
        $data = json_decode($data, true);

//      //重新设置缓存，有效期120分钟
//      Cache::put('access_token', $curl['access_token'], 120);

        return $data;
    }

}
